package vn.codespot.hms.model.response;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import vn.codespot.hms.utils.JSonUtils;
import vn.codespot.hms.utils.LogUtil;

public class AbsResponseModel implements IResponseModel {
    public static final int INVALID_ERROR_CODE = -1;
    public static final String SUCCESS = "SUCCESS";
    public static final String ERR_MSG = "err_msg";
    public static final String ERR_CODE = "err_code";
    public static final String RESULT = "result";

    private Set<String> mRespAttrNames;

    private Map<String, String> mRespValues;

    public AbsResponseModel() {
        mRespValues = new HashMap<String, String>();
        mRespAttrNames = new HashSet<String>();
        mRespAttrNames.add(RESULT);
        mRespAttrNames.add(ERR_CODE);
        mRespAttrNames.add(ERR_MSG);
    }

    public AbsResponseModel(Collection<String> respAttrNames) {
        this();
        mRespAttrNames.addAll(respAttrNames);
    }

    @Override
    public boolean isSuccess() {
        return mRespValues.get(RESULT) != null ? SUCCESS.equals(mRespValues.get(RESULT)) : false;
    }

    @Override
    public String getErrorMessage() {
        return mRespValues.get(ERR_MSG) != null ? mRespValues.get(ERR_MSG) : null;
    }

    @Override
    public int getErrorCode() {
        return mRespValues.get(ERR_CODE) != null ? Integer.valueOf(mRespValues.get(ERR_CODE)) : INVALID_ERROR_CODE;
    }

    public void parse(String json) {
        try {
            mRespValues.putAll(JSonUtils.getSingleAttributeValuePairs(mRespAttrNames, JSonUtils.getRootJSonObject(json)));
        } catch (Exception e) {
            LogUtil.e("Exception: ", e);
        }
    }

    @Override
    public String getResponseValue(String name) {
        return mRespValues.get(name);
    }
}
